package la.iok.hzsvn.lewin.movie.cloud.service;

import la.iok.hzsvn.lewin.movie.cloud.entity.OrgUnitAddress;
import la.iok.hzsvn.lewin.movie.cloud.mapper.OrgUnitAddressMapper;
import la.iok.hzsvn.lewin.mybatis.service.BaseServiceImpl;
import la.iok.hzsvn.share.address.Address;
import la.iok.hzsvn.share.address.AddressCode;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.annotations.NotNullElement;
import la.iok.hzsvn.share.annotations.Nullable;
import la.iok.hzsvn.share.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class OrgUnitAddressServiceImpl
        extends BaseServiceImpl<OrgUnitAddress,OrgUnitAddressMapper,Long>
        implements OrgUnitAddressService {

    public OrgUnitAddressServiceImpl(OrgUnitAddressMapper orgUnitAddressMapper) {
        super(orgUnitAddressMapper);
    }

    @Override
    public void save(@Nullable Long orgUnitId, @Nullable Address address) {
        if(orgUnitId == null || address == null){
            return;
        }
        OrgUnitAddress orgUnitAddress = orgUnitAddress(orgUnitId);
        if(orgUnitAddress == null){
            if(StringUtils.isBlank(address.getAddr()) && StringUtils.isBlank(address.getDetailAddress())){
                return;
            }
            mapper.insert(orgUnitId,address);
        } else {
            if(StringUtils.isBlank(address.getAddr()) && StringUtils.isBlank(address.getDetailAddress())){
                //都为空,那删除
                mapper.deleteById(orgUnitAddress.getId());
            }else{
                mapper.update(orgUnitAddress.getId(),address);
            }
        }
    }
    @Override
    public OrgUnitAddress orgUnitAddress(@Nullable Long orgUnitId) {
        if(orgUnitId == null){
            return null;
        }
        return mapper.selectByProperty("orgUnitId",orgUnitId);
    }

    @Override
    public int deleteOrgUnitAddress(@Nullable Long orgUnitId) {
        if(orgUnitId == null){
            return 0;
        }
        OrgUnitAddress orgUnitAddress = orgUnitAddress(orgUnitId);
        if(orgUnitAddress == null){
            return 0;
        }
        return mapper.deleteById(orgUnitAddress.getId());
    }

    @NotNull
    @NotNullElement
    @Override
    public List<OrgUnitAddress> list(@Nullable Collection<Long> orgUnitIds) {
        return listInProperty("orgUnitId",orgUnitIds);
    }

    @NotNull
    @Override
    public Address po2vo(@NotNull OrgUnitAddress address) {
        Address addr = new Address();
        BeanUtils.copyProperties(address,addr);
        AddressCode ac = new AddressCode(address.getProvince(),address.getCity(),address.getArea(),address.getTown());
        addr.setAddressCode(ac);
        return addr;
    }
}
